/**
 * 
 */
package com.cqan.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;

import com.cqan.account.entity.Permission;
import com.cqan.account.service.PermissionService;

/**
 * 
 * 加载资源与权限的对应关系
 * 
 * @author slaton
 * 
 *         下午05:22:59
 */
@Service("invocationSecurityMetadataSource")
public class InvocationSecurityMetadataSource implements
		FilterInvocationSecurityMetadataSource {

	private static final Logger logger = LoggerFactory.getLogger("ds.debug");

	
	private PermissionService permissionService;

	private static Map<String, Collection<ConfigAttribute>> resourceMap = null;

	public void loadResourceDefine() {
		if (resourceMap == null) {
			resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
		}
		List<Permission> permissions = permissionService.getAll();
		for (Permission permission : permissions) {
			Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();
			// 以权限名封装为Spring的security Object
			ConfigAttribute configAttribute = new SecurityConfig(permission.getCode());
			configAttributes.add(configAttribute);
			resourceMap.put("/"+permission.getResource().getUrl(), configAttributes);
		}
	}

	public Collection<ConfigAttribute> getAttributes(Object object)
			throws IllegalArgumentException {
		if (logger.isDebugEnabled()) {
			logger.debug("getAttributes(Object) - start");
		}
		String requestUrl = ((FilterInvocation) object).getRequestUrl();
		logger.debug("requestUrl is {}",new String[]{requestUrl});
		if (resourceMap == null) {
			loadResourceDefine();
		}
		return resourceMap.get(requestUrl);
	}

	public boolean supports(Class<?> clazz) {
		return true;
	}

	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	@Autowired
	public void setPermissionService(PermissionService permissionService) {
		this.permissionService = permissionService;
	}

	

	
}
